package com.lance.answer.gui.answer.gk.answer.lms.batch.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.lance.answer.dto.CompleteInfo;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.answer.lms.batch.dto.LmsWatchDTO;
import com.lance.answer.gui.answer.gk.answer.lms.util.LmsUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;


@Slf4j
public class DoUploadFileTask extends Thread {


    public static ExecutorService pool = Executors.newSingleThreadExecutor();

    private final String driverPath;
    private final LinkedBlockingDeque<LmsWatchDTO> watchDTOS;

    public DoUploadFileTask(String driverPath, LinkedBlockingDeque<LmsWatchDTO> watchDTOS) {
        this.driverPath = driverPath;
        this.watchDTOS = watchDTOS;
    }

    @SneakyThrows
    @Override
    public void run() {

        while (watchDTOS.size() > 0) {
            LmsWatchDTO lmsWatchDTO = watchDTOS.take();
            String userName = lmsWatchDTO.getUsername();
            String password = lmsWatchDTO.getPassword();
            log.info("任务：{} 剩余 {} 行 用户名：{} 密码：{}",
                    Thread.currentThread().getName(), watchDTOS.size(), userName, password);
            System.err.println("执行任务11111");
            run(driverPath, lmsWatchDTO);
        }

        if (watchDTOS.size() == 0) {
            log.info("课程所有用户均已执行完毕，系统将在20min后结束");
            TimeUnit.MINUTES.sleep(20);
            return;
        }
    }


    // 完型填空类型
    public static final String CLOZE = "subject ng-scope cloze";

    public static void run(String driverPath, LmsWatchDTO lmsWatchDTO) throws Exception {




        ChromeDriver driver = Util.getDriver(driverPath);
        try {
            String url = "https://menhu.pt.ouchn.cn/site/ouchnPc/index";
            driver.get(url);
            Thread.sleep(3000);

            String userName = lmsWatchDTO.getUsername();
            String pwd = lmsWatchDTO.getPassword();


            //  pool.submit(() -> LmsUtil.login(driver, userName, pwd));
            LmsUtil.login(driver, userName, pwd);

            TimeUnit.SECONDS.sleep(10);

            // 要求分数 FIXME 每个课程要求的分数不一样


            Map<Long, String> courseMap = lmsWatchDTO.getCourseMap();


            for (Long courseId : courseMap.keySet()) {
                // 这里只看 大作业
                String courseName = courseMap.get(courseId);
                log.info("开始答题.........{}",courseName);
                Set<String> urlTask = lmsWatchDTO.getUrlMap().get(courseName);
                study(driver,urlTask, courseName,userName);

            }

        } catch (Exception e) {

        } finally {
            try {
                driver.close();
                driver.quit();
            } catch (Exception e1) {

            }
        }
    }


    private static void study(WebDriver driver, Set<String> urlTasks, String subjectName,String userName) throws Exception {

        // 进入课程首页
        for (WebElement we : driver.findElements(By.cssSelector("div[class='ouchnPc_index_course_div']"))) {
            String textContent = we.getText();
            System.err.println("text:" + textContent);
            if (textContent.contains(subjectName)) {
                we.findElement(By.tagName("a")).click();
                Thread.sleep(6000);
                break;
            }
        }
        Util.switchToLast(driver);


        // TODO 现在开始获取具体课程所有的答题链接：：



        // https://lms.ouchn.cn/course/10000001767/learning-activity/full-screen#/10000213698

        String filePath = "libs//lmsAnswerInfo//"+ subjectName;
        //  String filePath = "D:\\project\\answer-tool\\libs\\answerInfo\\" + subjectName;

        if (!new File(filePath).exists()) {
            new File(filePath).mkdirs();
        }

        filePath = filePath + "//" + userName + "-upload.txt";

        File completeInfoFile = new File(filePath);
        if (!completeInfoFile.exists()) {
            completeInfoFile.createNewFile();
        }
        InputStream inputStream = new FileInputStream(completeInfoFile);
        String completeInfoStr = IOUtils.toString(inputStream, "UTF-8");
        List<CompleteInfo> completeInfoList = JSONObject.parseArray(completeInfoStr, CompleteInfo.class);
        if (null == completeInfoList) {
            completeInfoList = Lists.newArrayList();
        }

        List<String> haveCompleteHomeWorkUrlSet = Lists.newArrayList();

        for (CompleteInfo info : completeInfoList) {
            if (info.isComplete()) {
                haveCompleteHomeWorkUrlSet.add(info.getHomeworkUrl());
            }
        }

        boolean isReturn = true;
        for(String url:urlTasks){
            if(!haveCompleteHomeWorkUrlSet.contains(url)){
                isReturn = false;
                break;
            }
        }
        System.err.println("haveCompleteHomeWorkUrlSet:"+ JSON.toJSONString(haveCompleteHomeWorkUrlSet)+"\t  reytun:" +isReturn);
        if(isReturn){
            return;
        }


        for (String url: urlTasks) {
            try {

                // 排除不计入考核的作业

                driver.get(url);
               // Thread.sleep(8000);
                Thread.sleep(15000);
                // 点击我的作业
                driver.findElement(By.cssSelector("span[class='tab-title submission-tab left']")).click();
                Thread.sleep(1000);

                // TODO 这里判断是否提交了作业
                boolean isSubmit = false;

                for(WebElement spanWe:driver.findElements(By.cssSelector("span[class^='left submission-score error-tag ng-scope']"))){
                    if("未评分".equals(spanWe.getText())){
                        log.info("该课程已经评分啦：{}",subjectName);
                        isSubmit = true;

                        CompleteInfo completeInfo = new CompleteInfo();
                        completeInfo.setComplete(true);
                        completeInfo.setHomeworkUrl(url);
                        completeInfoList.add(completeInfo);
                        break;
                    }


                }

                if(isSubmit){
                    continue;
                }

                // 点击写作业
                for (WebElement spanWe : driver.findElements(By.cssSelector("span[class='ng-scope']"))) {
                    if (spanWe.getText().contains("写作业")) {
                        spanWe.click();
                        Thread.sleep(2000);
                        break;
                    }
                }


                Thread.sleep(2000);
                // 添加文件
                for(WebElement btnWe:driver.findElements(By.tagName("button"))){
                    if(btnWe.getText().contains("添加文件")){
                        btnWe.click();
                        Thread.sleep(2000);
                        break;
                    }
                }
                // tab-title ng-scope
                // 添加文件
                for(WebElement liWe:driver.findElements(By.cssSelector("li[class='tab-title ng-scope']"))){
                    if(liWe.getText().contains("本地上传")){
                        liWe.click();
                        Thread.sleep(2000);
                        break;
                    }
                }

               WebElement uploadAreaWe =   driver.findElement(By.cssSelector("div[class='popup-content ng-scope']"));

                uploadAreaWe.click();
                Thread.sleep(2000);

               // WebElement uploadWe  = driver.findElement(By.cssSelector("div[class='select-file']"));
               // WebElement uploadWe  = driver.findElement(By.cssSelector("div[class='upload-area']"));

                try {
                    System.err.println("1111111");
                    WebElement uploadWe  = uploadAreaWe.findElement(By.cssSelector("div[class='select-file']"));
                   uploadWe.click();
                   Thread.sleep(2000);
                    //D:\software\autoit\1.exe
                    //实现文件上传。通过Runtime的静态方法获取Runtime对象
                    Runtime runtime = Runtime.getRuntime();
                          //通过Runtime对象调用exe方法
                    Random random = new Random();
                  //  runtime.exec("D:\\software\\autoit\\1.exe");
                    runtime.exec("D:\\software\\autoit\\"+random.nextInt(10)+".exe");
                 //   runtime.exec("D:\\software\\autoit\\1.au3");

                    Thread.sleep(6000);

                    // 找到提交大作业的主界面
                    WebElement studentWorkAreaWe = driver.findElement(By.cssSelector("div[class='popup-content ng-scope']"));
                    studentWorkAreaWe.click();

                    for(WebElement liWe:driver.findElements(By.cssSelector("li[class='tab-title']"))){
                        if(liWe.getText().contains("资源库")){
                            liWe.click();
                            Thread.sleep(2000);
                            break;
                        }
                    }

                    // button button-green medium
                    for(WebElement btnWe:driver.findElements(By.cssSelector("button[class='button button-green medium']"))){
                        if(btnWe.getText().contains("确认")){
                            btnWe.click();
                            Thread.sleep(2000);
                            break;
                        }
                    }

                    for(WebElement btnWe:driver.findElements(By.tagName("button"))){
                        if(btnWe.getText().contains("交付作业")){
                            btnWe.click();
                            Thread.sleep(2000);
                            break;
                        }
                    }
                    //  uploadWe.sendKeys("F:\\国开WORD\\计算机应用基础(本)\\计算机应用基础(本).zip");
                }catch (Exception e){
                    e.printStackTrace();
                }


                // 提交答题并确认提交 button button-green ng-scope
               // Thread.sleep(500000);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        FileUtils.write(completeInfoFile, JSONObject.toJSONString(completeInfoList, SerializerFeature.PrettyFormat), "utf-8");
    }




}
